<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/8/16
 * Time: 16:00
 */
class Solr{

    private $connect;
    private $response;
    private $default_config_path = __DIR__.'/solr.json';

    public function __construct()
    {
        $solr_json = @file_get_contents($this->default_config_path);
        $option = json_decode($solr_json,true);
        $this->connect=new SolrClient($option);
    }

    //添加索引
    public function addIndex($data)
    {
        $doc= new SolrInputDocument();

        foreach ($data as $key=>$value)
        {
            $doc->addField($key,$value); // id  author name cat
        }
        $response=$this->connect->addDocument($doc);
        $this->executeResponse= $response->getResponse();
        $this->connect->commit();
    }

    //删除索引
    public function deleteById($id)
    {
        $this->connect->deleteByQuery("id:".$id);
        $this->connect->commit();
    }

   //查询索引
    public function query($keyword,$filed,$where=[])
    {
        $queryObject=new SolrQuery();

        $queryObject->setQuery($keyword);
        foreach ($where as $name=>$value)
        {
            $queryObject->addFilterQuery($name.":",$value);
        }
        foreach ($filed as $key=>$filed_name)
        {
            $queryObject->addField($filed_name);
        }
        $query_response = $this->connect->query($queryObject);
        $data = $query_response->getResponse()->response->docs;
        return $data;
    }

    public function getById($id)
    {
        $get_data =  $this->connect->getById($id);
        $http_status = $get_data->getHttpStatus();
        $data = $get_data->getResponse()->doc;
        if($http_status==200&&$data)
        {
            return $data ;
        }
        else{
            return false;
        }
    }
}